<template>
    <view class="page">
        <view class="header-line">互成一家</view>
        <scroll-view class="main-content" scroll-y="true" @scrolltolower="loadMore()">
            <view class="dashboard">
                <view class="user">
                    <view class="icon">
                        <view class="userIcon" :style="`--icon: url(${userIcon})`" @click="switchToTab('/pages/home/home')"></view>
                    </view>
                    <view class="say-hello">
                        <view class="hello" style="--font-size: 5vmin; font-weight: 900;">{{ helloOfTime }}</view>
                        <view class="say-text" style="--font-size: 3.5vmin; color: #222;">今天也要加油哦~</view>
                    </view>
                </view>
                <view class="stat">
                    <view class="stat-item" v-for="item in statList" :key="item.title">
                        <view class="count" style="--font-size: 5vmin; --font-color: rgb(26, 185, 108);">{{ item.count }}
                        </view>
                        <view class="title" style="--font-size: 3vmin; --font-color: #222;">{{ item.title }}</view>
                    </view>
                </view>
            </view>

            <view class="more-func-box">
                <view @click="switchToTab('/pages/focusPomodoro/focusPomodoro')">
                    <view class="icon" :style="`--icon: url(${ base_url }/static/img/kaishizhuanzhu.svg);`"></view>
                    <view class="title">开始专注</view>
                </view>
                <view @click="switchToTab('/pages/dynamic/dynamic')">
                    <view class="icon" :style="`--icon: url(${ base_url }/static/img/xunzhaohuoban.svg);`"></view>
                    <view class="title">寻找伙伴</view>
                </view>
                <view @click="switchToTab('/pages/hire/hire')">
                    <view class="icon" :style="`--icon: url(${ base_url }/static/img/gongwenbao.svg);`"></view>
                    <view class="title">校招信息</view>
                </view>
            </view>

            <view class="today-target">
                <view class="header">
                    <view class="title">今日目标</view>
                    <view class="show-all-btn" @click="navigateToNextPage('/pages/planList/planList')">查看全部</view>
                </view>
                <view class="main">
                    <view class="t-list" v-if="showTarget.length">
                        <view class="item" v-for="item in showTarget" :key="item.id" @click="openPlanBox(item)">
                            <view class="header">
                                <view class="title">{{ item.title }}</view>
                                <view class="remain-time">{{ item.checkinDay != item.count ? (item.isChecked ? '今日已完成' : '今日待完成') : '已全部完成' }}</view>
                            </view>
                            <view class="progress-box">
                                <view class="progress" :style="`--progress: ${item.progress};`"></view>
                                <view class="progress-text">{{ item.progress }}</view>
                            </view>
                        </view>
                    </view>
                    <view class="t-empty" v-else>
                        <view class="icon" :style="`background-image: url(${ base_url }/static/img/gantan.svg);`"></view>
                        <view class="text">贝贝 您目前还没有添加任何计划哦~</view>
                    </view>
                </view>
            </view>

            <view class="dynamics">
                <view class="header">
                    <view class="title">互助动态</view>
                    <view class="show-all-btn" @click="switchToTab('/pages/dynamic/dynamic')">查看全部</view>
                </view>
                <view class="dy-class" style="display: none;">

                </view>
                <view class="dy-list">
                    <CirclePostItem
                        v-for="item in dyList"
                        :key="item.id"
                        :id="String(item.id)"
                        :username="item.username"
                        :userIcon="item.userIcon"
                        :title="item.title"
                        :content="item.content"
                        :imgList="item.imgList"
                        :circlePostType="item.circlePostType"
                        :circlePostTypeTextColor="item.circlePostTypeTextColor"
                        :circlePostTypeBgColor="item.circlePostTypeBgColor"
                        :commentCount="parseInt(item.commentCount)"
                        :likeCount="parseInt(item.likeCount)"
                        :isLike="Boolean(item.isLike)"
                        :time="item.time"
                        @clickLikeBtn="clickLikeBtn"
                    />
                </view>
            </view>

            <!-- 检查用户是否同意用户协议的窗口 -->
            <view class="check-userAgreement-shadow" v-if="miniWinShow">
                <view class="check-userAgreement-box">
                    <view class="miniwin-header">
                        <view class="title">欢迎使用</view>
                    </view>
                    <view class="miniwin-main">
                        <view class="logo">
                            <image src="/static/img/logo.png"></image>
                        </view>
                        <view class="h1" style="--font-size: 5vmin;">让我们一起加入互成一家</view>
                        <view class="h2" style="--font-size: 3.5vmin;">登录后开启你的家人之旅</view>
                        <view class="check-line" @click="onCheckboxChange">
                            <view class="checkbox-border">
                                <view class="checkbox-checkmark" v-if="userAgreementCheckBox"></view>
                            </view>
                            <text style="--font-color: #000;">我已阅读并同意</text>
                            <text style="--font-color: rgb(26, 185, 108);">《用户协议》</text>
                            <text style="--font-color: #000;">和</text>
                            <text style="--font-color: rgb(26, 185, 108);">《隐私政策》</text>
                        </view>
                        <view class="btn-line">
                            <view class="login-btn" @click="agreementFunc">微信一键登录</view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 每日计划详情的窗口 -->
            <view class="plan-shadow" v-if="plan.isshow">
                <view class="plan-box">
                    <view class="miniwin-header">
                        <view class="title">计划详情</view>
                    </view>
                    <view class="miniwin-main">
                        <view class="plan-content">
                            <view class="group">
                                <view class="name">任务名称：{{ plan.taskName }}</view>
                            </view>
                            <view class="group">
                                <view class="name">任务描述：</view>
                                <view class="taskDesc">{{ plan.taskDesc }}</view>
                            </view>
                            <view class="group">
                                <view class="name">打卡进度：</view>
                                <view class="task-line-bottom-line">
                                    <view class="progress" :style="`--progress: ${ plan.progress }`"></view>
                                    <view class="progress-text">{{ plan.progress }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="btn-line">
                        <view class="no-btn" @click="closePlanBox">取消</view>
                        <view class="ok-btn" @click="checkinPlan" v-if="plan.checkinDay != plan.count">{{ plan.isChecked ? '已打卡' : '打卡' }}</view>
                    </view>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
// 服务层
import { user } from '../../server/user.js';
import { checkin } from '../../server/checkin.js';
import { plan } from '../../server/plan.js';
import { base_url } from '../../server/config';
// 业务层
import { getRecommendPostList } from '../../service/dynamic.js';
import { getPlanList } from '../../service/plan.js';
import { getUserInfo } from '../../service/user';

// 组件
import { CirclePostItem } from '../../components/common/CirclePostItem.vue';

// 锁
let lock = true;

export default {
    data() {
        return {
            base_url,
            // 用户信息
            username: "",
			userIcon: "",
			college: "",
			major: "",
			level: "",
			bio: "",
            // 主要内容
            helloOfTime: '早上好！',
            statList: [
                {
                    count: 0,
                    title: '今日专注'
                }, {
                    count: 0,
                    title: '连续打卡'
                }, {
                    count: 0,
                    title: '积分'
                }
            ],
            allTarget: [
                // {
                //     id: 1,
                //     icon: '',                    // 图标
                //     title: '背诵单词50个',        // 标题
                //     remainTime: '剩余2小时',      // 剩余时间
                //     progress: '70%'              // 进度百分比
                // }
            ],
            dyList: [
                // {
                //     id: 1,
                //     userIcon: '',
                //     username: '小明',
                //     title: '考研互助小组',
                //     content: '有没有准备考研的同学，一起组队互相监督呀~ 我准备考浙大计算机，最近在刷数学，找个一起学习的伙伴。每天打卡，互相分享学习进度和心得，一起进步！如果你也在准备考研，或者有相关经验，欢迎加入我们~',
                //  imgList: 'xxx',      -- 由 imgIdList 字段计算而来
                //     circlePostType: '学习',
                //  circlePostTypeTextColor: '',
                //  circlePostTypeBgColor: '',
                //     commentCount: 5,
                //     likeCount: 12,
                //     time: '10分钟前',     -- 由 publishTime 字段计算而来
                //  isLiked: false
                // }
            ],
            // 小窗口的样式
            miniWinShow: false,              // 当这个变量为true时 表示miniwin显示
            userAgreementCheckBox: false,    // 当这个变量为true时 表示用户已同意
            plan: {
                isshow: false,
                id: '',
                taskName: '',
                taskDesc: '',
                progress: '0%',
                isChecked: false,
                checkinDay: 0,
                count: 1
            }
        }
    },
    methods: {
        switchToTab(url) {
            uni.switchTab({ url });
        },
        navigateToNextPage(url) {
            uni.navigateTo({ url });
        },
        onCheckboxChange(e) {
            this.userAgreementCheckBox = !this.userAgreementCheckBox;  // 更新复选框状态
        },
        agreementFunc(e) {
            if (!this.userAgreementCheckBox) {
                uni.showToast({
                    icon: 'none',
                    title: '请先同意用户协议',
                    duration: 500
                });
            } else {
                uni.showToast({
                    icon: 'none',
                    title: '登录中...',
                    duration: 500
                });
                user.agreeUserAgreement().then(res => {
                    uni.showToast({
                        icon: 'none',
                        title: '登录成功',
                        duration: 500
                    });
                    this.miniWinShow = false;
                }).catch(err => {
                    uni.showToast({
                        icon: 'none',
                        title: '请检查网络',
                        duration: 500
                    });
                });
            }
        },
        loadMore() {
            if (!lock) return;
            lock = true;
            let lastId = this.dyList[this.dyList.length - 1].id;
            console.log('滑动到了页面底部', lastId);
            getRecommendPostList(this, lastId).then(() => {
                lock = false;
            });
        },
        setHelloOfTime() {
            let now_time = new Date();
            // 获取当前的小时数
            let hour = now_time.getHours();
            if (hour < 6) {
                this.helloOfTime = '凌晨好！';
            } else if (hour < 9) {
                this.helloOfTime = '早上好！';
            } else if (hour < 12) {
                this.helloOfTime = '上午好！';
            } else if (hour < 14) {
                this.helloOfTime = '中午好！';
            } else if (hour < 18) {
                this.helloOfTime = '下午好！';
            } else if (hour < 20) {
                this.helloOfTime = '傍晚好！';
            } else if (hour < 24) {
                this.helloOfTime = '晚上好！';
            }
            setTimeout(() => {
                this.setHelloOfTime();
            }, 1000 * 60 * 60);
        },
        clickLikeBtn(v) {
            console.log('接到通知', v);
            let dyList = this.dyList;
            for (let i = 0; i < dyList.length; i++) {
                if (dyList[i].id == v.id) {
                    dyList[i].isLike = v.isLike;
                    if (v.isLike) {
                        dyList[i].likeCount++;
                    } else {
                        dyList[i].likeCount--;
                    }
                    break;
                }
            }
        },
        openPlanBox(item) {
            this.plan.isshow = true;
            this.plan.id = item.id;
            plan.getPlanInfo(item.id).then(res => {
                this.plan.taskName = res.planInfo.name;
                this.plan.taskDesc = res.planInfo.description;
                this.plan.progress = `${((parseInt(res.planInfo.checkinDay) / parseInt(res.planInfo.count)) * 100).toFixed(2)}%`;
                this.plan.isChecked = res.planInfo.isCheckin;
                this.plan.checkinDay = parseInt(res.planInfo.checkinDay),
                this.plan.count = parseInt(res.planInfo.count)
            }).catch((err) => {
                uni.showToast({
                    icon: 'none',
                    title: '请检查网络',
                    duration: 500
                });
                setTimeout(() => {
                    this.plan.isshow = false;
                }, 400);
            });
        },
        closePlanBox() {
            this.plan.isshow = false;
            this.plan.id = '';
            this.plan.taskName = '';
            this.plan.taskDesc = '';
            this.plan.progress = '0%';
            this.plan.isChecked = false;
            this.plan.checkinDay = 0;
            this.plan.count = 1;
        },
        checkinPlan() {
            if (this.plan.isChecked) {
                uni.showToast({
                    icon: 'none',
                    title: '今日已打卡',
                    duration: 500
                });
                return ;
            }
            plan.checkinPlan(this.plan.id).then(res => {
                if (res.success) {
                    // 提示
                    uni.showToast({
                        icon: 'none',
                        title: '计划打卡成功',
                        duration: 500
                    });
                    // 关闭弹窗
                    this.closePlanBox();
                    // 获取打卡计划列表
                    getPlanList(this);
                } else {
                    uni.showToast({
                        icon: 'none',
                        title: res.msg,
                        duration: 500
                    });
                }
            }).catch((err) => {
                uni.showToast({
                    icon: 'none',
                    title: '请检查网络',
                    duration: 500
                });
            });
        }
    },
    computed: {
        showTarget() {
            return this.allTarget.slice(0, 3);
        },
        
    },
    components: {
        CirclePostItem
    },
    onLoad() {
        checkUserAgreement(this);      // 检查用户是否同意了用户协议
    },
    onShow() {
        // 获取用户信息
        getUserInfo(this);
        // 获取推荐帖子
        getRecommendPostList(this).then(() => {
            lock = false;
        });
        // 获取所有打卡计划
        getPlanList(this);
        this.setHelloOfTime();
        getMainPageNeedInfo(this);
    }
}

// 检查用户是否同意了用户协议
async function checkUserAgreement(self) {
    try {
        let res = await user.checkUserAgreement();
        if (res.success) {
            self.miniWinShow = !JSON.parse(res.termsAgreed);
        } else {
            self.miniWinShow = true;
        }
    } catch (err) {
        console.log(err);
    }
}

function getMainPageNeedInfo(self) {
    checkin.getMainPageNeedInfo().then(res => {
        if (res.success) {
            self.statList[0].count = res.data.today_duration || 0;
            self.statList[1].count = res.data.consecutiveDays || 0;
            self.statList[2].count = res.data.points || 0;
        } else {
            uni.showToast({
                icon: 'none',
                title: '请检查网络',
                duration: 500
            });
        }
    }).catch(err => {
        uni.showToast({
            icon: 'none',
            title: '请检查网络',
            duration: 500
        });
    });
}


</script>

<style>
.main-content {
    background-color: rgb(245, 245, 245);
    /* padding-bottom: 5vmin; */
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
    display: none;
    /* 隐藏滚动条 */
    width: 0;
    /* 设置滚动条宽度为0 */
    height: 0;
    /* 设置滚动条高度为0 */
    color: transparent;
    /* 设置滚动条颜色为透明 */
}

.page {
    --more-div-size: 16.5vmin;
    --more-func-icon-size: 8vmin;
}

/* 主页的内容 */

/* 用户仪表盘 */
.dashboard {
    width: 100%;
    height: 40vmin;
    margin-top: 4vmin;
    padding: 3vmin 0;
    background-color: #fff;
    border-radius: 3vmin;
}

.dashboard > view {
    width: 100%;
    height: 50%;
    margin: 0;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
}

.dashboard .icon {
    --size: 20vmin;
    width: var(--size);
    height: var(--size);
    position: relative;
    margin: 0 3vmin;
}

.dashboard .icon > .userIcon {
    --size: 70%;
    width: var(--size);
    height: var(--size);
    border-radius: 50%;
    background-color: rgb(245, 245, 245);
    background-image: var(--icon);
    background-size: 80%;
    background-repeat: no-repeat;
    background-position: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.dashboard .say-hello {
    flex: 1;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    gap: 1vmin;
}

.dashboard .say-hello > view {
    font-size: var(--font-size);
}

.dashboard .stat {
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-around;
    align-items: center;
}

.dashboard .stat .stat-item > view {
    font-size: var(--font-size);
    color: var(--font-color);
    text-align: center;
}

/* 更多功能 */
.more-func-box {
    width: 100%;
    height: 20vmin;
    margin-top: 4vmin;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
}

.more-func-box > view:first-child {
    background-color: rgb(7, 193, 96);
    color: #fff;
}

.more-func-box > view {
    width: 30%;
    height: 100%;
    background-color: #fff;
    color: #222;
    font-size: 3.5vmin;
    position: relative;
    border-radius: 3vmin;
}

.more-func-box .icon {
    width: 100%;
    height: 6vmin;
    margin-top: 4vmin;
    margin-bottom: 1vmin;
    background-image: var(--icon);
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
}

.more-func-box .title {
    text-align: center;
}

/* 今日目标 */
.today-target,
.dynamics {
    box-sizing: border-box;
    width: 100%;
    height: auto;
    margin-top: 4vmin;
    padding: 4vmin;
    border-radius: 3vmin;
    background-color: #fff;
}

.today-target > .header,
.dynamics > .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 4vmin;
}

.today-target > .header .title,
.dynamics > .header .title {
    font-size: 4vmin;
    font-weight: 600;
}

.today-target > .header .show-all-btn,
.dynamics > .header .show-all-btn {
    font-size: 4vmin;
    color: #666;
}

.today-target > .main {
    display: flex;
    flex-direction: column;
    gap: 4vmin;
}

.today-target > .main .item {
    background: #f8f8f8;
    border-radius: 2vmin;
    margin-bottom: 3vmin;
    padding: 4vmin;
}

.today-target > .main .item > .header {
    display: flex;
    justify-content: left;
    align-items: center;
    margin-bottom: 3vmin;
}

.today-target > .main .icon {
    width: 4vmin;
    height: 4vmin;
    background-position: center;
    background-size: cover;
}

.today-target > .main .title {
    font-size: 4vmin;
    font-weight: 700;
    margin-left: 2vmin;
    max-width: 70%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.today-target > .main .t-empty {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
    padding: 10vmin 0;
    gap: 3vmin;
    font-size: 3.5vmin;
}

.today-target .remain-time {
    text-align: right;
    flex: 1;
    font-size: 3vmin;
    color: #666;
}

.today-target .progress-box {
    display: flex;
    align-items: center;
    gap: 3vmin;
}

.today-target .progress {
    flex: 1;
    height: 1.5vmin;
    background: #eee;
    border-radius: 0.75vmin;
    overflow: hidden;
}

.today-target .progress::after {
    content: "";
    display: block;
    width: var(--progress);
    height: 100%;
    background: #07c160;
    border-radius: 0.75vmin;
    transition: width .3s ease;
}

.today-target .progress-text {
    font-size: 3vmin;
    color: #07c160;
    min-width: 9vmin;
}

/* 互助动态区域 */
.dynamics {
    margin-bottom: 5vmin;
    padding-bottom: 20vmin;
    position: relative;
}

.dynamics::after {
    content: "已经到底拉~";
    display: block;
    position: absolute;
    left: 50%;
    bottom: 5vmin;
    transform: translateX(-50%);
    font-size: 3vmin;
}

/* 检查用户是否同意用户协议的窗口 */
.check-userAgreement-shadow {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: #8888;
}

.check-userAgreement-box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 80vmin;
    height: 110vmin;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border-radius: 3vmin;
    display: flex;
    flex-direction: column;
}

.check-userAgreement-shadow .miniwin-header {
    display: flex;
    padding: 5vmin;
    border-bottom: 0.1vmin solid #ccc;
}

.check-userAgreement-shadow .title {
    font-size: 4vmin;
}

.check-userAgreement-shadow .miniwin-main {
    flex: 1;
    padding: 5vmin;
}

.check-userAgreement-shadow .logo {
    width: 100%;
    height: 20vmin;
    text-align: center;
    margin-bottom: 6vmin;
}

.check-userAgreement-shadow .logo image {
    width: 20vmin;
    height: 20vmin;
}

.check-userAgreement-shadow .h1,
.check-userAgreement-shadow .h2 {
    text-align: center;
    font-size: var(--font-size);
    margin-bottom: 4vmin;
}

.check-userAgreement-shadow .check-line {
    display: flex;
    font-size: 3vmin;
    margin-top: 10vmin;
}

.check-userAgreement-shadow .check-line text {
    color: var(--font-color);
}

.check-userAgreement-shadow .checkbox-border {
    --size: 3vmin;
    width: var(--size);
    height: var(--size);
    margin-right: 1vmin;
    padding: 0.5vmin;
    border: 0.1vmin solid #ccc;
    border-radius: 0.3vmin;
}

.check-userAgreement-shadow .checkbox-checkmark {
    --size: 100%;
    width: var(--size);
    height: var(--size);
    background-color: rgb(26, 185, 108);
}

.check-userAgreement-shadow .btn-line {
    margin-top: 10vmin;
    text-align: center;
}

.check-userAgreement-shadow .login-btn {
    --h: 10vmin;
    width: 90%;
    height: var(--h);
    line-height: var(--h);
    background-color: rgb(7, 193, 96);
    text-align: center;
    border-radius: 1vmin;
    margin: 0 auto;
    font-size: 4vmin;
    color: #fff;
}

.check-userAgreement-shadow .login-btn:active {
    background-color: rgb(13, 161, 85);
}

/* 计划详情 */
.plan-shadow {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: #8888;
}

.plan-shadow .plan-box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 80vmin;
    max-height: 110vmin;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border-radius: 3vmin;
    display: flex;
    flex-direction: column;
}

.plan-shadow .miniwin-header {
    display: flex;
    padding: 5vmin;
    border-bottom: 0.1vmin solid #ccc;
}

.plan-shadow .title {
    font-size: 4vmin;
}

.plan-shadow .miniwin-main {
    flex: 1;
    padding: 5vmin;
    overflow-y: auto;
}

.plan-shadow .plan-content {
    font-size: 3.5vmin;
    flex: 1;
}

.plan-shadow .group {
    margin-bottom: 5vmin;
}

.plan-shadow .taskDesc {
    text-indent: 2em;
    overflow-wrap: break-word;
}

.plan-shadow .task-line-bottom-line {
    margin-top: 3vmin;
    display: flex;
    align-items: center;
    gap: 3vmin;
}

.plan-shadow .progress {
    flex: 1;
    height: 2.5vmin;
    background: #eee;
    border-radius: 1vmin;
    overflow: hidden;
}

.plan-shadow .progress::after {
    content: "";
    display: block;
    width: var(--progress);
    height: 100%;
    background: #07c160;
    border-radius: 3px;
    transition: width .3s ease;
}

.plan-shadow .progress-text {
    font-size: 3vmin;
    color: #07c160;
    min-width: 9vmin;
}

.plan-shadow .btn-line {
    display: flex;
    gap: 3vmin;
    padding: 5vmin;
    border-top: 0.1vmin solid #ccc;
}

.plan-shadow .btn-line > view {
    /* --h: 10vmin; */
    flex: 1;
    /* height: var(--h);
    line-height: var(--h); */
    text-align: center;
    margin: 0 auto;

    padding: 2vmin 0;
    border-radius: 5vmin;
    font-size: 3.5vmin;
    border: none;
    transition: all .2s ease;
}

.plan-shadow .ok-btn {
    background-color: rgb(7, 193, 96);
    color: #fff;
}

.plan-shadow .no-btn {
    background-color: #ccc;
    color: #000;
}

.plan-shadow .ok-btn:active {
    background-color: rgb(13, 161, 85);
}
</style>
